from decimal import Decimal

from django.db import connection

from app.decorator import jwt_auth
from app.service import stats
from libs import time_helper
from libs.common import success, error
from libs.form import RawJsonForm


@jwt_auth
def sales(request, auth):
    shop_id = auth.get('shop_id')
    form = RawJsonForm(request.body)
    flag = form.get_int('flag', 0)
    from_time = form.get('from_time', '')
    to_time = form.get('to_time', '')
    stats_label = '销售统计'
    label_map = {
        'k1': '应收金额',
        'k2': '退款金额',
        'k3': '实际销售额',
        'k4': '线上APP',
        'k5': '线下店铺',
        'k6': '仓储卡累计充值金额',
        'k7': '已使用抵扣券数量',
        'k8': '今日待发放抵扣券的订单数量',
        'k9': '下一次抵扣券发放时间',
        'k10': '商品热销TOP10',
        'k11': '收款情况',
        'k12': '会员新增数量',
        'k13': '累计会员数量',
        'k14': '仓储卡当前余额',
        'k15': '余额累计充值金额',
        'k16': '余额当前余额',
        'k17': '有消费会员数量',
        'k18': '剩余抵扣券数量',
        'k19': '抵扣累计发放券数量',
        'k20': '抹零金额',
        'k21': '会员卡累计充值金额',
        'k22': '会员卡当前余额',
    }
    if flag == 1:
        stats_label = '今日销售统计'
        from_time = time_helper.date_str({'days': 0})
        to_time = time_helper.date_str({'days': 1})
        label_map.update({
            'k1': '今日应收金额',
            'k2': '今日退款金额',
            'k6': '今日仓储储值',
            'k7': '今日已发放抵扣券数量',
            'k9': '下一次抵扣券发放时间',
            'k10': '今日商品热销TOP10',
            'k12': '今日会员新增数量',
        })
    elif flag == 2:
        from_time = ''
        to_time = ''
    else:
        from_ts = time_helper.time_str_to_ts(from_time, time_format='%Y-%m-%d')
        to_ts = time_helper.time_str_to_ts(to_time, time_format='%Y-%m-%d') + 86400
        if not (from_ts > 0 and to_ts > 0):
            return error('无效的时间范围')
        flag = 0
        stats_label = '{} - {}销售统计'.format(from_time, to_time)
        to_time = time_helper.ts_to_time_str(to_ts, '%Y-%m-%d')

    stats_result = []
    with connection.cursor() as cursor:
        app_order_sale_amount_dec = stats.stats_shop_sales_amount(cursor, shop_id, from_time, to_time, stats.SELL_STATE, filters=['order_type=0'])

        app_order_sale_refund_dec = stats.stats_shop_sales_amount(cursor, shop_id, from_time, to_time, stats.RETURN_STATE, filters=['order_type=0'])  # App退款金额

        cs_order_sale_amount_1 = stats.stats_shop_cs_sales_amount(cursor, shop_id, from_time, to_time, '-1,1')
        cs_order_sale_amount_2 = stats.stats_shop_cs_sales_amount(cursor, shop_id, from_time, to_time, '-2')
        # k1_val = app_order_sale_amount_dec - app_order_sale_refund_dec + cs_order_sale_amount_1 - cs_order_sale_amount_2
        k1_val = app_order_sale_amount_dec + cs_order_sale_amount_1 - cs_order_sale_amount_2
        stats_result.append({
            'key': 'k1',
            'val': k1_val
        })
        # time_range_all_refund_dec = stats.stats_shop_sales_amount(cursor, shop_id, from_time, to_time, stats.RETURN_STATE)  # 今日退款金额
        time_range_all_refund_dec = stats.stats_shop_sales_amount(cursor, shop_id, from_time, to_time, stats.RETURN_STATE,filters=['order_type=1']) # 今日退款金额
        stats_result.append({
            'key': 'k2',
            'val': time_range_all_refund_dec
        })
        time_range_actual_sales_dec = stats.stats_shop_sales_amount(cursor, shop_id, from_time, to_time, stats.SELL_STATE)  # 实际销售金额
        k3_val = time_range_actual_sales_dec - time_range_all_refund_dec
        stats_result.append({
            'key': 'k3',
            'val': k3_val
        })
        # 线上APP
        time_range_app_actual_sales_dec = stats.stats_shop_sales_amount(cursor,
                                                                        shop_id,
                                                                        from_time, to_time,
                                                                        stats.SELL_STATE,
                                                                        filters=['order_type=0'])
        time_range_app_actual_sales_return_dec = stats.stats_shop_sales_amount(cursor,
                                                                               shop_id,
                                                                               from_time, to_time,
                                                                               stats.RETURN_STATE,
                                                                               filters=['order_type=0'])
        stats_result.append({
            'key': 'k4',
            'val': (time_range_app_actual_sales_dec - time_range_app_actual_sales_return_dec).quantize(Decimal('0.00'))
        })

        # 线下店铺
        time_range_cs_actual_sales_dec = stats.stats_shop_sales_amount(cursor,
                                                                       shop_id,
                                                                       from_time, to_time,
                                                                       stats.SELL_STATE,
                                                                       filters=['order_type=1'])
        time_range_cs_actual_sales_return_dec = stats.stats_shop_sales_amount(cursor,
                                                                              shop_id,
                                                                              from_time, to_time,
                                                                              stats.RETURN_STATE,
                                                                              filters=['order_type=1'])
        stats_result.append({
            'key': 'k5',
            'val': (time_range_cs_actual_sales_dec - time_range_cs_actual_sales_return_dec).quantize(Decimal('0.00'))
        })

        stats_storage_result = stats.stats_storage(cursor,shop_id, from_time, to_time)
        # 仓储卡储值
        cs_sales_amount = stats_storage_result.get('amount')
        stats_result.append({
            'key': 'k6',
            'val': cs_sales_amount
        })

        # 收款情况
        shop_payment_stats = stats.stats_shop_payment(cursor, shop_id, from_time, to_time)
        stats_result.append({
            'key': 'k11',
            'val': shop_payment_stats
        })

        # 今日会员新增数量
        shop_mem_num = stats.stats_shop_member_num(cursor, shop_id, from_time, to_time)
        stats_result.append({
            'key': 'k12',
            'val': shop_mem_num
        })

        # 累计会员数量
        shop_mem_total = stats.stats_shop_member_num(cursor, shop_id)
        stats_result.append({
            'key': 'k13',
            'val': shop_mem_total
        })

        # 已发放抵扣券数量
        stats_rebate_already_give_out = stats.stats_shop_rebate(cursor, shop_id, from_time, to_time)
        stats_result.append({
            'key': 'k7',
            'val': stats_rebate_already_give_out
        })

        # 待发放抵扣券的订单数量
        k17_val = stats.stats_have_order_member_num(cursor, shop_id, from_time, to_time)
        stats_result.append({
            'key': 'k17',
            'val': k17_val
        })

        sale_ranking = stats.sales_ranking(cursor, shop_id, from_time, to_time)
        stats_result.append({
            'key': 'k10',
            'val': sale_ranking
        })

        if flag == 1:
            # 待发放抵扣券的订单数量
            k8_val = stats.stats_rebate_to_be_give_out(cursor, shop_id, from_time, to_time)
            stats_result.append({
                'key': 'k8',
                'val': k8_val
            })
            # 下一次抵扣券发放时间
            stats_rebate_pub_time = stats.get_next_rebate_give_out_time(cursor)
            stats_result.append({
                'key': 'k9',
                'val': stats_rebate_pub_time
            })
        storage_total = stats.stats_mem_storage_total(cursor)
        stats_result.append({
            'key': 'k14',
            'val': storage_total
        })
        k15_val = stats.stats_balance_top_up_total(cursor)
        stats_result.append({
            'key': 'k15',
            'val': k15_val
        })
        k16_val = stats.stats_mem_balance_total(cursor)
        stats_result.append({
            'key': 'k16',
            'val': k16_val
        })
        k18_val = stats.stats_mem_coupon_total(cursor)
        stats_result.append({
            'key': 'k18',
            'val': k18_val
        })
        k19_val = stats.stats_mem_rebate_total(cursor, from_time, to_time)
        stats_result.append({
            'key': 'k19',
            'val': k19_val
        })

        k20_val_sell_row = stats.stats_price_to_int(cursor, shop_id, '-1,1', from_time, to_time)
        k20_val_refund_row = stats.stats_price_to_int(cursor, shop_id, '-2', from_time, to_time)

        sell_total_price = Decimal('0')
        sell_cart_total_price = Decimal('0')
        refund_total_price = Decimal('0')
        refund_cart_total_price = Decimal('0')
        if k20_val_sell_row is not None:
            if k20_val_sell_row[0] is not None:
                sell_total_price = k20_val_sell_row[0]
            if k20_val_sell_row[1] is not None:
                sell_cart_total_price = k20_val_sell_row[1]
        if k20_val_refund_row is not None:
            if k20_val_refund_row[0] is not None:
                refund_total_price = k20_val_refund_row[0]
            if k20_val_refund_row[1] is not None:
                refund_cart_total_price = k20_val_refund_row[1]
        k20_val = sell_cart_total_price - sell_total_price + refund_cart_total_price - refund_total_price
        stats_result.append({
            'key': 'k20',
            'val': k20_val
        })
        k21_val = stats.stats_fastballance_charge_total(cursor)
        stats_result.append({
            'key': 'k21',
            'val': k21_val
        })
        k22_val = stats.stats_mem_fastbalance_total(cursor)
        stats_result.append({
            'key': 'k22',
            'val': k22_val
        })
        for stats_item in stats_result:
            stats_item.update({
                'label': label_map.get(stats_item.get('key'), '')
            })
    return success(stats_result, label=stats_label, flag=flag)
